package com.ubi.core.framework.validation;

public class SafeStringValidateUtils {

    public static final String REGEX_TAG = "((%3C)|<)((%2F)|/)*[a-z0-9%]+((%3E)|>)";

    public static final String REGEX_EVAL = "(\\s|\\S)*((%65)|e|E)(\\s)*((%76)|v|V)(\\s)*((%61)|a|A)(\\s)*((%6C)|l|L)(\\s|\\S)*";

    public static final String REGEX_SCRIPT = "(\\s|\\S)*((%73)|s|S)(\\s)*((%63)|c|C)(\\s)*((%72)|r|R)(\\s)*((%69)|i|I)(\\s)*((%70)|p|P)(\\s)*((%74)|t|T)(\\s|\\S)*";

    public static final String REGEX_MYSQL_KEYWORDS = "(\\s|\\S)*(\\b((or)|(and)|(count)|(char)|(chr)|(mid))\\b)(\\s|\\S)*";

    public static final String REGEX_MYSQL_SYMBOL = "( \\s|\\S)*((%27)|(')|(%3D)|(=)|(/)|(%2F)|(\")|((%22)|(-|%2D){2})|(%23)|(%3B)|(;)|(\\|))+(\\s|\\S)*";

    public static final String KEYWORDS = "exec|insert|select|delete|union|update|*|%|master|truncate|declare|+|,|like|where|hostname";

    public static boolean validate(String value) {
        if (null == value)
            return true;
        if (!validateContainsXSSString(value))
            return false;
        return validateContainsSqlInjectString(value);
    }

    static boolean validateContainsXSSString(String value) {
        // 匹配任意开闭标签
        if (value.matches(REGEX_TAG))
            return false;
        // Eval XSS 屏蔽关键字 eval
        if (value.matches(REGEX_EVAL))
            return false;
        // Script XSS 屏蔽关键字 script
        return !value.matches(REGEX_SCRIPT);
    }

    static boolean validateContainsSqlInjectString(String text) {
        String value = text.toLowerCase();
        // 不允许包含下列关键字
        for (String keyword : KEYWORDS.split("\\|")) {
            if (value.contains(keyword))
                return false;
        }
        // 不允许包含下列关键字 or and count char chr mid
        if (value.matches(REGEX_MYSQL_KEYWORDS))
            return false;
        // 不允许包含符号: ' = / " (" -- # ; |
        if (value.matches(REGEX_MYSQL_SYMBOL))
            return false;
        // 不允许包含MySql注解 ;%00
        return !value.contains(";%00");
    }
}
